<?php
namespace app\wx\controller;
use think\facade\Cache;
use think\Db;
class Wx extends Basewx
{

	

    public function verification(){
        if($_POST['token']){
            echo '123';
        }
    }


    public function channel(){
        return $this->fetch('yaoqing');
    }




    public function power_rate(){
    	$userinfo = session('wxgzh');
    	$room = Db::name('tenant')
		    ->Leftjoin('ty_room',['ty_tenant.house_id=ty_room.house_id','ty_tenant.room_id=ty_room.r_id'])
            ->Leftjoin('ty_housing_resources',['ty_tenant.house_id=ty_housing_resources.hr_id',])
            ->Leftjoin('ty_business_circle',['ty_business_circle.bc_id=ty_housing_resources.hr_bc_id',])
            ->Leftjoin('ty_residential_quarters',['ty_residential_quarters.rq_bc_id=ty_business_circle.bc_id',])
	        ->where('tenant_phone',session('wxgzh')['phone'])
		    ->find();
        if (!$room) {
            echo '<script>alert("未查询到电费数据");window.location.href="/wx/user/center"</script>';
            die;
        }
		//dump(Db::getLastSql());
//		dump($room);
//		dump(session('wxgzh'));
		// echo $room['con_house_cqdz'].$room['room_num'].'号房间<br>';
		// echo $room['tenant_sex'].'快一度';
		// echo $room['tenant_balance'].'元钱<br>';
		$room['tenant_sex'] = $room['tenant_sex']/100;
		// $room['tenant_balance'] =-100;
		$room['tenant_balance'] = $room['tenant_balance']/100;
        $this->assign('url',$this->myurl);
        $this->assign('userinfo',$userinfo);
        $this->assign('room',$room);
        return $this->fetch();
    }


    //微信推送事件
    public function index(){
        $valid = $this->model->valid();
        if (!$valid){
            exit('数据错误');
        }
        //获取微信返回的xml消息
        $xmldata = file_get_contents("php://input");
        file_put_contents('userdata.txt',PHP_EOL.$xmldata.PHP_EOL,FILE_APPEND);
        //将$xmldata解析为对象
        $postObj = simplexml_load_string($xmldata,'SimpleXMLElement',LIBXML_NOCDATA);
        //将$postObj对象强制转换成数组
        $data = (array)$postObj;
        file_put_contents('userdata.txt',PHP_EOL.json_encode($data,JSON_UNESCAPED_SLASHES).PHP_EOL,FILE_APPEND);
        //dump($data);
        //事件推送
        if(isset($data['MsgType'])&&$data['MsgType']=='event'){
            //关注
            if($data['Event']=='subscribe'){
                $this->seng_user_msg($data['FromUserName'],'欢迎');
                $this->model->subscribe($data);
            }
            //取消关注
            if($data['Event']=='unsubscribe'){
                $this->model->unsubscribe($data);
            }
            //定位
            if($data['Event']=='LOCATION'){
                $this->model->location($data);
            }
        }
        //消息推送
        if(isset($data['MsgType'])){
            $this->robot($data);
        }
        echo $_GET['echostr'];

    }

    //获取accesstoken
    public function get_access_token(){
        $cache_token = 'access_token';
        $access_token = Cache::get($cache_token);
        if($access_token){
            return $access_token;
        }else{
            $iscache=true;
            return $this->model->access_token($iscache);
        }
    }
    //获取微信ip列表
    public function get_wx_list(){
        $token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token='.$token;
        return $this->curl_get($url);
    }

    //获取微信ip列表
    public function curl_get($url,$header=array()){
//        $header = array(
//            'Content-Type: application/json',
//        );
        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_POST, true);//设置post方式提交
        curl_setopt($ch, CURLOPT_URL, $url);//设置抓取的url
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $returnText);//设置post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以字符流的形式返回，而不是直接输出
        curl_setopt($ch,CURLOPT_HEADER,0);//是否输出页面内容
        curl_setopt($ch,  CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//抓取页面的等待时间为30秒
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        $response = curl_exec($ch);//执行命令
        if ($response === FALSE){
            echo 'cURL Error:'.curl_error($ch);
        }
        curl_close($ch);//关闭URL请求
        return $response;
    }

    //自定义菜单
    public function custom_menu(){
        $access_token = $this->model->access_token();
        if(!$access_token){
            exit('access_token获取失败');
        }
        dump($access_token);
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $data = '{
            "button": [
                {
                    "type": "view", 
                    "name": "首页", 
                    "url": "https://taoyuanapartment.com/"
                }, 
                {
                    "type": "view", 
                    "name": "个人中心", 
                    "url": "http://admin.taoyuanapartment.com/wx/user/center"
                }, 
                {
                    "name": "测试", 
                    "sub_button": [
                        {
                            "type": "view", 
                            "name": "用户信息", 
                            "url": "http://admin.taoyuanapartment.com/wx/index/auth"
                        },
                        {
                            "type": "view", 
                            "name": "用户地理位置", 
                            "url": "http://admin.taoyuanapartment.com/wx/index/location.html"
                        },
                        {
                            "type": "view", 
                            "name": "红包", 
                            "url": "http://hypay.top/"
                        }
                    ]
                }
            ]
        }';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 设置请求方式为post
        curl_setopt($ch, CURLOPT_POST, true);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        // 请求头，可以传数组
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($ch);
        curl_close($ch);
        dump($res);
    }

    //微信网页授权，获取当前用户昵称头像信息
    //用户同意授权获取code，通过code换取access——token，刷新access——token，拉去用户信息（需要scope为snsapi——userinfo）
    public function auth(){
        //回调地址，执行userinfo方法
        $redirect = 'http://admin.taoyuanapartment.com/index.php/wx/index/userinfo';
        //echo(urlEncode($redirect));die;
        //按钮跳转地址
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wx.appid').'&redirect_uri='.urlEncode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header('Location:'.$url);
    }

    //显示用户信息
    public function userinfo(){
        //通过auth()方法获取code
        $code = input('get.code');
        file_put_contents('weixincode.txt',$code);
        //使用auth_access_token($code,false)方法得到网页授权access_token
        $res = $this->model->auth_access_token($code,false);
        $auth_access_token = $res['access_token'];
        $openid = $res['openid'];
        //拉取用户信息(需scope为 snsapi_userinfo)
        $userinfo = $this->model->get_userinfo($auth_access_token,$openid);
        dump($userinfo);
    }

    // 获取用户地理位置，JSSDK方式
    public function location(){
        $data['appid'] = config('wx.appid');
        $data['timestamp'] = time();
        $data['nonceStr'] = md5(time().rand(1,999));
        // 生成签名
        // 1、获取jsapi_ticket
        $access_token = $this->model->access_token();//获取普通token
        //dump($access_token);
        $jsapi_ticket = $this->model->jsapi_ticket($access_token,false);//获取签名
        //file_put_contents('res.txt',$jsapi_ticket);
        // 2、构造签名字符串
        $params['noncestr'] = $data['nonceStr'];
        $params['jsapi_ticket'] = $jsapi_ticket;
        $params['timestamp'] = $data['timestamp'];
        //$params['url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $params['url'] = 'http://admin.taoyuanapartment.com/index.php/wx/index/location.html';
        ksort($params);//对key做排序
        //dump($params);
        $str = urldecode(http_build_query($params));//防止url字符转义
        //echo $str;die;
        // 3、生成签名
        $data['signature'] = sha1($str);//使用sha1加密
        //dump($data);die;
        return $this->fetch('',$data);
    }

    // 机器人接口
    private function robot($data){
        file_put_contents('robdata',var_export($data,true));
        if($data['MsgType'] == 'image' || ['MsgType'] == 'voice' || ['MsgType'] == 'video' || ['MsgType'] == 'shortvideo' || ['MsgType'] == 'link'){
            $response = $this->model->img_article_msg($data);
            exit($response);
        }
        // 调用器机人聊天
        $response = $this->model->robot($data);
//        $response = '<xml><ToUserName>'.$data['FromUserName'].'</ToUserName>
//<FromUserName>'.$data['ToUserName'].'</FromUserName>
//<CreateTime>1528269940</CreateTime>
//<MsgType>text</MsgType>
//<Content>故障</Content>
//<MsgId>6563869412233738189</MsgId>
//</xml>';
        exit($response);
    }

    public function kefu(){
        $access_token = $this->get_access_token();
        $add = 'https://api.weixin.qq.com/customservice/kfaccount/add?access_token='.$access_token;
        $del = 'https://api.weixin.qq.com/customservice/kfaccount/del?access_token='.$access_token;
        $getkflist = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token='.$access_token;
        $update = 'https://api.weixin.qq.com/customservice/kfaccount/update?access_token='.$access_token;
        //$uploadheadimg = 'https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token='.$access_token.'&kf_account='.$kf_account;
        $json = json_encode(array('kf_account'=>'test1@test','nickname'=>'客服1','password'=>md5('123456')));
        dump($json);
        function curl_post($url,$json){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            // 执行后不直接打印出来
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            // 设置请求方式为post
            curl_setopt($ch, CURLOPT_POST, true);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
            // 请求头，可以传数组
            curl_setopt($ch, CURLOPT_HEADER, false);
            // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            // 不从证书中检查SSL加密算法是否存在
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $res = curl_exec($ch);
            curl_close($ch);
            dump($res);
        }
        curl_post($add,$json);
        curl_post($getkflist,$json);

    }

    public function seng_user_msg($openid,$msg='Hello World'){
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
        $json = json_encode(array('touser'=>$openid,'msgtype'=>'text','text'=>['content'=>$msg]),JSON_UNESCAPED_UNICODE);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 设置请求方式为post
        curl_setopt($ch, CURLOPT_POST, true);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        // 请求头，可以传数组
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($ch);
        curl_close($ch);
        dump($res);
    }

    public function nearapartment(){
        if(empty($_GET)){
            $data['appid'] = config('wx.appid');
            $data['timestamp'] = time();
            $data['nonceStr'] = md5(time().rand(1,999));
            // 生成签名
            // 1、获取jsapi_ticket
            $access_token = $this->model->access_token();//获取普通token
            //dump($access_token);
            $jsapi_ticket = $this->model->jsapi_ticket($access_token,false);//获取签名
            //file_put_contents('res.txt',$jsapi_ticket);
            // 2、构造签名字符串
            $params['noncestr'] = $data['nonceStr'];
            $params['jsapi_ticket'] = $jsapi_ticket;
            $params['timestamp'] = $data['timestamp'];
            //$params['url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            $params['url'] = 'http://admin.taoyuanapartment.com/index.php/wx/index/nearapartment';
            ksort($params);//对key做排序
            //dump($params);
            $str = urldecode(http_build_query($params));//防止url字符转义
            //echo $str;die;
            // 3、生成签名
            $data['signature'] = sha1($str);//使用sha1加密
            //dump($data);//die;
            return $this->fetch('',$data);
        }else{
            $lat = $_GET['latitude'];
            $lng = $_GET['longitude'];
            $this->model->get_location_address($lat,$lng);
        }
    }

    public function tests(){

        /*echo '929ffc531f44942578d2c1494ed2232104d509a3<br>';
        $timestamp = 1527495586;
        $nonce = 973958226;
        $token = 'phpcn';
        $sign = sha1($timestamp.$nonce.$token);
        exit($sign);*/
        $params['appid'] = '10001';
        $key = '4fa92702a0633127d26ba957d97680ab';
        $params['timestamp'] = time();
        $params['msg'] = input('get.msg');
        ksort($params);
        $str = http_build_query($params);
        $sign = sha1($str.$key);
        $url = 'http://tests.php.cn/index.php/weixintest/robot?'.$str.'&sign='.$sign;

        $res = http_get($url);
        $res = json_decode($res,true);
        dump($res);
    }
}
